//
//  GeWebAuditCell.swift
//  ANOA
//
//  Created by 邱仙凯 on 2024/9/29.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
 import WebKit
class GeWebAuditHeader: UIView, WKNavigationDelegate, WKUIDelegate {
 
    var commonWebview = WKWebView()
    var reportUrl:String? // 网页路径
    var pathUrl:String? // 本地路径
    /// 是否需要自动编码
    var needEncode = true
    fileprivate lazy var progress: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 5)
        progress.backgroundColor = #colorLiteral(red: 0.1803921569, green: 0.1960784314, blue: 0.568627451, alpha: 1)
        return progress
    }()
    
    var webSaveSuccessClo:(()->())?
    var limitWebSave:(() -> Void)!
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        limitWebSave = rateLimited(interval: 1) {
            if let clo = self.webSaveSuccessClo {
                clo()
            }
        }
     
 
     let config = WKWebViewConfiguration()
     config.preferences = WKPreferences()
     config.preferences.minimumFontSize = 18
     config.processPool = WKProcessPool()
//    config.preferences.javaScriptEnabled = true
        
        // 创建WKUserContentController实例，用于与JavaScript进行通讯
        let contentController = WKUserContentController()
        
        // 注册消息处理器，监听JavaScript中的消息
        contentController.add(self, name: "downloadHandler")
        contentController.add(self, name: "callbackHandler")


        // 配置WebView使用contentController
        config.userContentController = contentController
        

    self.backgroundColor = .clear
     self.backgroundColor = UIColor.clear
     commonWebview = WKWebView(frame: CGRect(x:0,y:0,width:KSGlobal.screenW,height:300), configuration: config)
     
        //添加webView
        commonWebview.navigationDelegate = self
        commonWebview.uiDelegate = self
      self.addSubview(commonWebview)
     // 用约束能更好的适配旋转屏
     commonWebview.snp.makeConstraints { (make) in
         make.left.right.top.bottom.equalTo(self)
     }
     
  }
    func startShowContent() {
        if let urlstr = reportUrl {
            var dealStr:String = ""
            if  self.needEncode {
                dealStr = urlstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            } else {
                dealStr = urlstr
            }
            if let url = URL(string: dealStr) {
                KSLog(url)
                // 不缓存
                commonWebview.load(URLRequest(url: url,cachePolicy: .reloadIgnoringLocalCacheData))
            } else {
                KSToast("url有误")
            }
        }
        
        if let pUrl = pathUrl {
            let url = URL(fileURLWithPath: pUrl)
            commonWebview.load(URLRequest(url: url))
        }
    }
 
 required init?(coder: NSCoder) {
     fatalError("init(coder:) has not been implemented")
 }
 
  

 
}

// MARK: navigationDelegate
extension GeWebAuditHeader:WKScriptMessageHandler {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIView.animate(withDuration: 0.55, animations: { () -> Void in
            self.progress.alpha = 0.0;
        })
        
        
        let saveCode = """
        function saveSuccess() {
            window.webkit.messageHandlers.callbackHandler.postMessage("handle save Func!");
        }
        """
        
        
        // 直接注入 JavaScript 代码
              let fileCode = """
              (function() {
                  // 保存原始的 downLoadMobilePreview 函数（如果存在）
                  if (typeof window.downLoadMobilePreview === "function") {
                      window.originalDownLoadMobilePreview = window.downLoadMobilePreview;
                  }
                  // 重写 downLoadMobilePreview 函数
                  window.downLoadMobilePreview = function(url,fileName) {
                      // 使用 postMessage 将消息发送回 Swift
                      if (window.webkit && window.webkit.messageHandlers.downloadHandler) {
                          window.webkit.messageHandlers.downloadHandler.postMessage({ url: url,fileName:fileName });
                      }
                      // 如果需要，可以调用原始的 downLoadMobilePreview 函数（如果存在）
                        var originalFunction = window.originalDownLoadMobilePreview;
                        if (originalFunction) {
                            originalFunction(url);
                        }
                  };
              })();
              """
        
        webView.evaluateJavaScript(saveCode) { (result, error) in
            if let error = error {
                print("Error injecting JS: \(error)")
            } else {
                print("save code injected successfully.")
            }
        }
    
        webView.evaluateJavaScript(fileCode) { (result, error) in
            if let error = error {
                print("Error injecting JS: \(error)")
            } else {
                print("fileCode code injected successfully.")
            }
        }
        
        
        
        
        
        
        
        
   
        //通过走mobileOpenHtmlErrorClick方法来试探一下是不是超时，该重新登录
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            
            self.commonWebview.evaluateJavaScript("mobileOpenHtmlErrorClick()", completionHandler: { (result, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else {
                    KSToast("登录超时，重新登录")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) {
                        // 没有error 执行成功了，真的需要重新登录了
                          LifeCycleTool.shared.logout()
                    }
                }
            })
            
//            //服务端要求调用的方法，功能是让必填校验正确执行
//            self.commonWebview.evaluateJavaScript("setFiledCan()", completionHandler: { (result, error) in
//             
//            })
            
            
            
          }
    }
    
    
    
    
    // 接收JavaScript发送的消息
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "callbackHandler" {
            print("JavaScript sent")
          
            KSToast("单据保存成功")
            self.limitWebSave()
           
        }
        if message.name == "downloadHandler", let args = message.body as? [String: Any] {
            
            let urlString = args["url"] as? String
            let titleString = args["fileName"] as? String
            
            KSLog("相应---")
            KSLog(titleString)
            KSLog(urlString)

              let cwebV = CommonWebController()
                cwebV.reportUrl = urlString
                cwebV.title = titleString
            RouterUtils.currentTopViewController()!.navigationController?.pushViewController(cwebV, animated: true)
            
            
              }
 
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("加载出了点问题")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
    }
}
